package com.example.demo.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.example.demo.dao.CarDao;
import com.example.demo.pojo.CarGood;

@RestController
public class GoodsController {
	@Autowired
	CarDao carDao;
//	@GetMapping({"/","/index"})
//	public String index() {
//		return "index";
//	}
	
	
//	[
//	    {
//	        "id":"5",
//	        "name":"5"
//	    },
//	    {
//	        "id":"6",
//	        "name":"6"
//	    }
//	]
    @PostMapping("addGood")
    public Map addGood(@RequestBody List<CarGood> goods) {
    	System.out.println(goods);
    	String result="no";
    	Map m=new HashMap();
    	try {
    		for(CarGood good:goods)
    			carDao.save(good);
    		result="yes";
    	}catch(Exception e){
    		throw e;
    	}
    	m.put("result", result);
    	return m;
    }
    @PostMapping("deleteGood")
    public Map deleteGood(@RequestBody List<CarGood> goods) {
    	System.out.println(goods);
    	String userId=new String();
    	String goodId=new String();
    	String result="no";
    	Map m=new HashMap();
    	try {
    		for(CarGood good:goods) {
    			System.out.println(good);
    			goodId=good.getGoodId();
    			userId=good.getUserId();
    			carDao.deleteByUserIdAndGoodId(userId,goodId);
    		}
    		result="yes";
    	}catch(Exception e){
    		throw e;
    	}
    	m.put("result", result);
    	return m;
    }
    @GetMapping("getAllGood")
    public Map<String, List<CarGood>> getAllGood(String id) {
    	ArrayList<String> goods=new ArrayList<String>();
		List<CarGood> all= carDao.findByUserId(id);
//		for(CarGood good:carDao.findAll()) {
//			String goodJson=JSON.toJSONString(good);
//			goods.add(goodJson);
//			System.out.println(goodJson);
//		}
//		int size=goods.size();
//		String info[]=(String[])goods.toArray(new String[size]);
		Map<String,List<CarGood>> map=new HashMap<String,List<CarGood>>();
		map.put("list", all);
		System.out.println(map.toString());
		return map;
    }
    //    @GetMapping("/test")
//    public String test() {
//        return "test";
//    }
}
